package com.zhuhanpeng.cloud.spring.security;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bjc:
 * @create 2023-02-19 下午 2:09
 * 用于记录用户登录失败次数和检查是否需要输入验证码。
 * loadUserByUsername方法中增加对用户密码输入次数的判断，
 * 当用户输入密码错误次数超过3次时，就将该用户的登录状态设为需要输入验证码的状态。
 * 然后，在登录页面进行验证码的校验，只有当用户处于需要输入验证码的状态时才需要校验验证码。
 */
@Service
public class LoginAttemptService {
    private Map<String, Integer> attempts = new HashMap<>();
    private Map<String, Boolean> needCaptcha = new HashMap<>();
    private final int MAX_ATTEMPT = 3;

    public void loginSucceeded(String username) {
        attempts.remove(username);
        needCaptcha.remove(username);
    }

    public void loginFailed(String username) {
        int attemptCount = attempts.getOrDefault(username, 0);
        attempts.put(username, attemptCount + 1);
        if (attemptCount + 1 >= MAX_ATTEMPT) {
            needCaptcha.put(username, true);
        }
    }

    public boolean isNeedCaptcha(String username) {
        return needCaptcha.getOrDefault(username, false);
    }

    public void resetUserAttempt(String username) {
        attempts.remove(username);
        needCaptcha.remove(username);
    }
}